import { login, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes || []
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    removeUserInfo(state) {
      state.userInfo = {}
    },
    setRoutes(state, filterRoutes) {
      state.routes = [...constantRoutes, ...filterRoutes, {
        path: '*',
        redirect: '/404',
        hidden: true
      }]
    }
  },
  actions: {
    async login(context, data) {
      const result = await login(data)
      context.commit('setToken', result)
    },
    async getUserInfo(context) {
      // 获取返回值
      const result = await getUserInfo()
      // 将整个的个人信息设置到用户的 Vuex 数据中
      context.commit('setUserInfo', result)
      return result
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('setUserInfo', {})
      resetRouter()
      context.commit('user/setRoutes', [], { root: true })
    }
  }
}
